﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Maverick.Domain.Abstract;
using Maverick.Domain.Entities;
using Maverick.WebUI.Models;

namespace Maverick.Controllers
{
    public class ThreadsController : Controller
    {
        private IMessagesRepository messagesRepository;

        public ThreadsController(IMessagesRepository messagesRepository)
        {
            this.messagesRepository = messagesRepository;
        }
 
        public ActionResult List()
        {
            var threads = messagesRepository.Messages.Where(x => x.ParentID == 0);
            var categories = messagesRepository.Categories.ToList();

            var model = new ThreadListViewModel {Categories = categories, Messages = threads.ToList()};
            
            return View(model);
        }

        public ActionResult Edit(int messageID)
        {
            var message = messagesRepository.Messages.First(x => x.MessageID == messageID);
            return View(message);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Message message)
        {
            if (ModelState.IsValid)
            {
                messagesRepository.SaveMessage(message);

                return RedirectToAction("List", "Threads");
            }

            return View(message);
        }

        public ActionResult Delete(int messageID)
        {
            var messages = messagesRepository.Messages.Where(x => x.MessageID == messageID || x.ParentID == messageID);

            foreach (Message message in messages)
            {
                messagesRepository.DeleteMessage(message);
            }

            return RedirectToAction("List");
        }

        public ActionResult Add(int categoryID)
        {
            Message message = new Message { DateTime = DateTime.Now, CategoryID =  categoryID};
            return View("Edit", message);
        }
    }
}
